<template>
  <!-- :ok-button-props="{ disabled: !isCompleted }" -->
  <a-modal :open="open" width="1000px" :title="rowData?.id ? '修改班制' : '新增班制'" :footer="false" centered @cancel="onCancel">
    <a-tabs v-model:activeKey="tabActiveKey" class="tab-overflow">
      <a-tab-pane :key="1" tab="基本信息">
        <a-form class="form-style-flex" :model="formState" :colon="false" :label-col="{ style: { width: '80px' } }">
          <a-form-item label="班制名称" class="w-1/2" v-bind="validateInfos.schdName">
            <a-input v-model:value="formState.schdName" placeholder="请输入" @blur="onChangeEmpName" />
          </a-form-item>
          <a-form-item label="助记码" class="w-1/2" v-bind="validateInfos.zjm">
            <a-input v-model:value="formState.zjm" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="顺序号" class="w-1/2" v-bind="validateInfos.outOrder">
            <a-input v-model:value="formState.outOrder" placeholder="请输入" />
          </a-form-item>
          <a-form-item label="类别" class="w-1/2" v-bind="validateInfos.type">
            <a-radio-group v-model:value="formState.type">
              <a-radio value="0">医生排班</a-radio>
              <a-radio value="1">护士排班</a-radio>
            </a-radio-group>
          </a-form-item>

          <a-form-item label="备注" class="w-full">
            <a-textarea v-model:value="formState.memo" :rows="10" placeholder="请输入" />
          </a-form-item>
        </a-form>
        <div class="flex justify-end">
          <a-button class="mr-2" @click="onCancel">取消</a-button>
          <a-button type="primary" :disabled="!isCompleted" @click="onSave">保存</a-button>
        </div>
      </a-tab-pane>
      <a-tab-pane :key="2" tab="班制时间" :disabled="!formState.schdCode">
        <div class="h-[362px] overflow-hidden">
          <BaseTable
            :data-source="dataSource"
            column-code="000243"
            :loading="loading"
            :height="200"
            :row-class-name="(record) => (record.isNew ? 'table-row-new' : '')"
            :scroll="{ x: 1400 }"
          >
            <template #bodyCell="{ column, record, index }">
              <template v-if="column.dataIndex === 'xh'">
                {{ index + 1 }}
              </template>
              <template v-if="column.dataIndex === 'stTime'">
                <EditCell title="开始时间">
                  <a-time-picker v-model:value="record.stTime" placeholder="请选择" value-format="HH:mm" format="HH:mm" @change="editRow(record)" />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'edTime'">
                <EditCell title="结束时间">
                  <a-time-picker v-model:value="record.edTime" placeholder="请选择" value-format="HH:mm" format="HH:mm" @change="editRow(record)" />
                </EditCell>
              </template>

              <template v-if="column.dataIndex === 'appStTime'">
                <EditCell title="预约开始时间">
                  <a-time-picker v-model:value="record.appStTime" placeholder="请选择" value-format="HH:mm" format="HH:mm" @change="editRow(record)" />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'appEdTime'">
                <EditCell title="预约结束时间">
                  <a-time-picker v-model:value="record.appEdTime" placeholder="请选择" value-format="HH:mm" format="HH:mm" @change="editRow(record)" />
                </EditCell>
              </template>

              <template v-if="column.dataIndex === 'ghlb'">
                <EditCell title="挂号类别">
                  <a-select
                    v-model:value="record.ghlb"
                    :disabled="formState.type === '1'"
                    :options="deptTypeList"
                    placeholder="请选择"
                    @change="onSelectChange($event, record)"
                  />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'ghfmc'">
                <EditCell title="挂号费别">
                  <SelectTable v-model:value="record.ghfmc" type="挂号费别" :disabled="formState.type === '1'" @select="onSelectRegistration($event, record)" />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'zlfmc'">
                <EditCell title="诊疗费别">
                  <SelectTable
                    v-model:value="record.zlfmc"
                    type="诊疗费别"
                    :disabled="formState.type === '1'"
                    @select="onSelectDiagnosisFees($event, record)"
                  />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'quantityLimit'">
                <EditCell title="限号">
                  <BaseInput
                    v-model:value="record.quantityLimit"
                    v-input:int
                    :disabled="formState.type === '1'"
                    @blur="editRow(record)"
                    @keydown.enter="editRow(record)"
                  />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'visitInterval'">
                <EditCell title="就诊时间间隔">
                  <BaseInput
                    v-model:value="record.visitInterval"
                    v-input:int
                    :disabled="formState.type === '1'"
                    @blur="editRow(record)"
                    @keydown.enter="editRow(record)"
                  />
                </EditCell>
              </template>
              <template v-if="column.dataIndex === 'action'">
                <BaseButton confirm-text="确定删除？" danger size="small" type="text" @click="onClickDelete(record)">删除</BaseButton>
              </template>
            </template>
            <template #footer>
              <div class="text-center sticky">
                <a-button class="mr-2" type="primary" ghost @click="addRow()"> 新增一行 </a-button>
                <!-- <a-button type="primary" :disabled="dataSource.length === 0" @click="saveNewRows()"> 保存 </a-button> -->
              </div>
            </template>
          </BaseTable>
          <div class="flex justify-end mt-8">
            <a-button class="mr-2" @click="onCancel">取消</a-button>
            <a-button type="primary" :disabled="!dataSource.some((i) => i.isNew === true)" @click="saveNewRows()">保存</a-button>
          </div>
        </div>
      </a-tab-pane>
    </a-tabs>
  </a-modal>
</template>
<script setup>
import { ref, watch, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { post } from '@/utils/request'
// import { getSystemConfig } from '@/utils/systemConfig'

const emit = defineEmits(['update:open', 'success'])
const props = defineProps({
  open: Boolean,
  rowData: {
    type: Object,
    default: () => ({})
  }
})

const loading = ref(false)
const tabActiveKey = ref(1)
const deptTypeList = ref([])
const dataSource = ref([])
const formState = ref({
  schdName: '',
  zjm: '',
  outOrder: '',
  type: ''
})
const rulesState = ref({
  schdName: [{ required: true, message: '请输入班制名称' }],
  zjm: [{ required: true, message: '请输入助记码' }],
  outOrder: [{ required: true, message: '请输入顺序号' }],
  type: [{ required: true, message: '请选择分类' }]
})
const { isCompleted, resetFields, validateInfos } = useForm(formState, rulesState)

// 挂号类别
const getDeptTypeList = async () => {
  const { code, data } = await post('/outp/mzdj/getRegistrationTypeList')
  if (code !== 0) return
  deptTypeList.value = data.map((item) => {
    return {
      label: item.ghlb,
      value: item.ghlbid
    }
  })
}

// 获取助记码
const onChangeEmpName = async (e) => {
  const { data, code, msg } = await post('/common/util/getPinyin', {
    name: e.target.value
  })
  if (code !== 0) return message.error(msg)
  formState.value.zjm = data
}

// 获取班制时间列表
const getData = async () => {
  loading.value = true
  const { data, code, msg } = await post('/operation/scheduling/getSchedulingTimeList', { schdCode: formState.value.schdCode })
  if (code !== 0) return message.error(msg)
  dataSource.value = data
  loading.value = false
}

//添加行
const addRow = async () => {
  const key = `row-${dataSource.value.length}`
  const addRow = { key, isNew: true }
  dataSource.value.push(addRow)
}

const onSelectChange = (val, row) => {
  row.ghlbId = val
  editRow(row)
}

const saveNewRows = async () => {
  const newRowList = dataSource.value.filter((item) => item.isNew)
  if (!newRowList.length) return message.error('请先新增一行')
  newRowList.forEach((item) => {
    if ((item.stTime && item.edTime && item.ghlb && item.ghfmc && item.zlfmc) || formState.value.type === '1') {
      fetchSave(item)
    } else {
      message.destroy()
      message.error('请填写完整信息')
    }
  })
}

const onClickDelete = async (row = {}) => {
  if (row.id) {
    const { code, msg } = await post('/operation/scheduling/doDelOutpSchedulingTime', { id: row.id })
    if (code !== 0) return message.error(msg)
    message.success(msg)
    getData()
  } else {
    dataSource.value = dataSource.value.filter((item) => item.key !== row.key)
    message.success('删除成功')
  }
}

const onSelectRegistration = (row, record) => {
  record.ghfId = row.bh
  record.ghfmc = row.mc
  record.ghfdj = row.dj
  record.zfy = Number(record.ghfdj || 0) + Number(record.zlfdj || 0)
}
const onSelectDiagnosisFees = (row, record) => {
  record.zlfId = row.bh
  record.zlfmc = row.mc
  record.zlfdj = row.dj
  record.zfy = Number(record.ghfdj || 0) + Number(record.zlfdj || 0)
}

const onSave = async () => {
  const { code, msg, data } = await post('/operation/scheduling/saveScheduling', { ...formState.value, outpSchedulingTimeList: dataSource.value })
  if (code !== 0) return message.error(msg)
  formState.value = { ...formState.value, ...data }
  message.success(msg)
  getData()
}

// 保存
const editRow = (row) => !row.isNew && fetchSave(row)

const fetchSave = async (row) => {
  const { code, msg } = await post('/operation/scheduling/saveScheduling', {
    ...formState.value,
    outpSchedulingTimeList: dataSource.value
  })
  if (code !== 0) return message.error(msg || '操作失败')
  message.destroy()
  message.success(row.isNew ? '新增成功' : '修改成功')
  getData()
}

const onCancel = () => {
  resetFields()
  emit('update:open', false)
  emit('success')
}

watch(
  () => props.open,
  (val) => {
    if (val) {
      tabActiveKey.value = 1
      formState.value = { ...props.rowData }
      formState.value.status = props.rowData.status ? 0 : 1
      formState.value.schdCode && getData()
      !formState.value.schdCode && (dataSource.value = [])
    }
  }
)

watch(
  () => tabActiveKey.value,
  (val) => {
    if (val === 2) {
      getData()
    }
  }
)

onMounted(() => {
  getDeptTypeList()
})
</script>
<style lang="less" scoped></style>
